<?php session_start();
$host = $_SERVER['HTTP_HOST'];
if ($_SERVER['SERVER_NAME'] == 'localhost'){$uri="/kalender";}else{$uri="";}
if (!isset($_SESSION['id_user']) || $_SESSION['id_user']=='') {
	echo "<script language=Javascript> location.href='http://$host$uri/index.php'; </script>";	
}else{
		
	if (!is_object($bd)){	
		//me conecto a la base de datos
		require("../globals/Db.class.php");
		require("../globals/Conf.class.php");
		$bd=Db::getInstance();	
	}
	if (!is_object($util)){	
		include("../globals/Util.class.php");		
		$util=Util::getInstance();
	}
	
	
	
	if (!($util->administrarTiempoSesion())){
		echo "<script language=Javascript> location.href='http://$host$uri/timeout.php'; </script>";
	}else if (!($util->administrarAcceso("facturacion"))){
		echo "<script language=Javascript> location.href='http://$host$uri/sinAcceso.php'; </script>";
	}else{	
		$idOT = $_POST['idOT'];
		$idNC = $_POST['idNC'];
		$idCli = $_POST['idCli'];
				
		try {
			$bd->beginTransaction();
				//si la OT no esta creada, la creo.
				if($idOT=='empty'){
					$query .= "insert into ordenes_trabajo (estado, id_cliente, fecha_creacion) values ('A', $idCli, now());";
					$result = $bd->eje($query);
					if ($result) $idOT = $bd->lastID();
					
					//guardo el log por auditoria
					$id_user = $_SESSION['id_user'];
					$query = "INSERT INTO logs (usuario_id, accion, fecha) values ($id_user, 'Se ha creado la Orden de Trabajo Nro: $idOT', now());";
					$bd->eje($query);
				}
				
				$query = "insert into nc_ot_relation (id_nc, id_ot) values ($idNC, $idOT);";
				$result = $bd->eje($query);
				
				$query = "update notas_credito set estado = 'U' where id = $idNC;";
				$result = $bd->eje($query);
				
			$bd->commit();
			echo "msg:ok##$idOT";
		} catch (Exception $e) {	   
	    	$bd->rollback();
			echo "msg:nok$e##$idOT";
		}
		
	}
	
}
?>